package com.wuhongyu.service.impl;

import com.wuhongyu.base.BaseServiceImpl;
import com.wuhongyu.common.MyCommon;
import com.wuhongyu.entity.Product;
import com.wuhongyu.entity.Storage;
import com.wuhongyu.repository.StorageDao;
import com.wuhongyu.service.StorageService;
import com.wuhongyu.util.MyUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service("storageService")
public class StorageServiceImpl extends BaseServiceImpl<Storage> implements StorageService {

    private StorageDao storageDao;
    @Resource
    public void setDao(StorageDao storageDao){
        super.setBaseDao(storageDao);
        this.storageDao = storageDao;
    }

    @Override
    public Page<Storage> findAll(Storage storage, Integer number) {
        Specification<Storage> spec = (root, query, cb) ->{
            Join<Storage,Product> root1 = root.join("product",JoinType.LEFT);
            List<Predicate> list = new ArrayList<>();
            if(storage.getProduct()!=null && MyUtil.notEmpty(storage.getProduct().getName()))
                list.add(cb.like(root1.get("name"),"%"+storage.getProduct().getName()+"%"));
            if(MyUtil.notEmpty(storage.getAddress()))
                list.add(cb.like(root.get("address"),storage.getAddress()));
            return cb.and(list.toArray(new Predicate[list.size()]));
        };
        return storageDao.findAll(spec,new PageRequest(MyUtil.getCurrentPage(number),MyCommon.PAGESIZE));
    }

}